package com.example.learndemo.JVM.String;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MyClassLoader extends ClassLoader {
    private String classPath;
    public MyClassLoader(String classPath){
        this.classPath=classPath;
    }
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String s = name.replaceAll("\\.", "/");
        try (FileInputStream fileInputStream = new FileInputStream(classPath + "/" + s+".class")) {
            int len = fileInputStream.available();
            byte[] bytes = new byte[len];
            fileInputStream.read(bytes);
            fileInputStream.close();
            return defineClass(name,bytes,0,len);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.findClass(name);
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return super.loadClass(name);
    }

    public static void main(String[] args) {
        MyClassLoader c=new MyClassLoader("D://");
        try {
            Class<?> aClass = c.loadClass("test.User");
            aClass.newInstance();
            System.out.println(aClass.getClassLoader().getClass().getName());
        } catch (ClassNotFoundException e) {

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}
